class Main extends eui.UILayer {

    public gameManager: manager.GameManager;

    public coin = 0;

    public extPage: page.ExtPage;

    private static instance: Main;

    public curPage: string;


    public static getInstance(): Main {
        return Main.instance
    }

    public constructor() {
        super();
        Main.instance = this;
    }

    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
        });

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        };

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        };

        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
        this.initGame();
    }

    private initGame() {
        console.log('initGameinitGame')
        let gameManager = manager.GameManager.getInstance();
        this.gameManager = gameManager;
        gameManager.init(this.stage, "xyxsj1533171252",
            "wx1577c18df656b23d", "一起方块消消消");
        gameManager.addEventListener(manager.GameManager.INIT_COMPLETE,
            this.onGameInitComplete, this);
        gameManager.addEventListener(manager.GameManager.GAME_SIZE_CHANGED,
            this.onGameSizeChanged, this);
        this.addChild(gameManager);
        egret.lifecycle.addLifecycleListener((context) => {
            context.onUpdate = () => {
            }
        });
        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        };
        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        };
    }

    private onGameSizeChanged(eve: egret.Event): void {
        facade.GameFacade.getInstance().resize();
    }

    // private onGameInitComplete(eve: egret.Event): void {
    //     this.runGame().catch(e => {
    //         console.log(e);
    //     });
    // }

    private async runGame() {
        await this.loadResource();
        this.createGameScene();
    }

    private async loadResource() {
        try {
            await RES.loadConfig("resource/default.res.json", "resource/");
            let preloadResourceItems = RES.getGroupByName("preload");
            let gameResourceItems = RES.getGroupByName("game");
            let commonKeys = [];

            let preloadKeys = [];
            preloadResourceItems.forEach(function (item, idx, array) {
                preloadKeys.push(item.name);
            });

            let gameKeys = [];
            gameResourceItems.forEach(function (item, idx, array) {
                gameKeys.push(item.name);
            });

            let gameManager: manager.GameManager = manager.GameManager.getInstance();
            RES.createGroup("game_res", commonKeys.concat(preloadKeys).concat(gameKeys), true);
            await this.loadTheme();
            await RES.loadGroup("game_res", 0, gameManager.getLoadUI());
            gameManager.hideLoadingUI();
        } catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private onGameInitComplete(eve: egret.Event): void {
        //盒子 or 游戏
        console.log('onGameInitComplete')
        console.log(manager.GameManager.GAME_TYPE)
        if (manager.GameManager.GAME_TYPE == "game") {
            this.runGame().catch(e => {
                console.log(e);
            });
        } else {
            if (!this.extPage) {
                this.extPage = new page.ExtPage(manager.DisplayManager.STAGE_WIDTH, manager.DisplayManager.STAGE_HEIGHT);
                this.addChild(this.extPage);
            } 
        }
    }

    private gameAdWidget: game.GameAdPage;

    private createGameScene() {

        this.curPage = "index";

        manager.GameManager.getInstance().adManager.showBannerAd();

        if (!manager.GameManager.getInstance().adManager.isChecking()) {
            if (this.gameAdWidget == null) {
                this.gameAdWidget = new game.GameAdPage();
            }
            manager.GameManager.getInstance().getUIManager().addTopWidget(this.gameAdWidget);
        }

        // if(Number(manager.GameManager.getInstance().adManager.ad_percent) % 10 === 0){
            // manager.GameManager.getInstance().getUserManager().login();
        // }

        facade.GameFacade.getInstance().init();
        let roomId: string = manager.GameManager.getInstance().getLaunchOptionsManager().getOption(manager.LaunchOptionsManager.ROOM_ID);
        if (roomId.length > 0) {
            // this.showInviteTip(roomId);
        }


        // let that = this;
        // wx.onShow(res => {
        //     egret.log("wx.onShow:", res);
        //     // let roomId: string = manager.LaunchOptionsManager.getOptionValue(res.query, "room_id");
        //     // if (roomId.length > 0) {
        //     //     this.showInviteTip(roomId);
        //     // }
        //     let shareTicket: string = res.shareTicket || "";
        //     if (shareTicket.length > 5) {
        //         let event: events.SceneEvent = new events.SceneEvent(game.SceneIds.RANK_SCENE_ID, {
        //             isShowGroup: true,
        //             shareTicket: shareTicket
        //         }, events.SceneEvent.POPUP_SHOW_TYPE);
        //         facade.GameFacade.getInstance().dispatchEvent(event);
        //     }
        // });
    }

    // public getGameManager(): manager.GameManager {
    //     return this.gameManager;
    // }
    // private showInviteTip(roomId: string): void {
    //     egret.log("roomId:", roomId);
    //     let invitePkPage: game.InviteTipPage = new game.InviteTipPage(roomId);
    //     manager.GameManager.getInstance().getUIManager().addGameWidget(invitePkPage);
    // }
}
